package com.zyx.tl.transmittable.inheritabletl;

import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;

/**
 * <p>InheritableThreadLocal类可以完成父线程到子线程的值传递。</p>
 * <p>但对于使用线程池等会缓存线程的组件的情况，线程由线程池创建好，并且线程是缓存起来反复使用的；</p>
 * <p>这时父子线程关系的ThreadLocal值传递已经没有意义，应用需要的实际上是把任务提交给线程池时的ThreadLocal值传递到任务执行时</p>
 *
 * @author Yaxi.Zhang
 * @since 2022/8/18 08:52
 */
public class CustomThreadLocal {
    static ThreadLocal<String> threadLocal = new InheritableThreadLocal<>();
    static ExecutorService pool = Executors.newFixedThreadPool(2);

    public static void main(String[] args) {
        for (int i = 0; i < 100; i++) {
            int j = i;
            // try {
            //     TimeUnit.MILLISECONDS.sleep(100);
            // } catch (InterruptedException e) {
            //     e.printStackTrace();
            // }
            pool.execute(new Thread(() -> {
                CustomThreadLocal.threadLocal.set("zyx" + j);
                new Service().call();
            }));
        }
    }
}
